package com.proton.carepatchtemp.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.graphics.RectF;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.ViewDragHelper;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.apkfuns.logutils.LogUtils;
import com.facebook.drawee.view.SimpleDraweeView;
import com.nineoldandroids.view.ViewHelper;
import com.proton.carepatchtemp.R;
import com.proton.carepatchtemp.application.VCare;
import com.proton.carepatchtemp.base.BaseActivity;
import com.proton.carepatchtemp.constant.Codes;
import com.proton.carepatchtemp.constant.Extras;
import com.proton.carepatchtemp.database.daomanager.ProfileManager;
import com.proton.carepatchtemp.database.table.Device;
import com.proton.carepatchtemp.database.table.Profile;
import com.proton.carepatchtemp.fragment.ChooseProfileFragment;
import com.proton.carepatchtemp.fragment.RealTimeTestFragment;
import com.proton.carepatchtemp.fragment.ReportListFragment;
import com.proton.carepatchtemp.fragment.SearchDevicesFragment;
import com.proton.carepatchtemp.fragment.SettingFragment;
import com.proton.carepatchtemp.fragment.SystemMsgCenterFragment;
import com.proton.carepatchtemp.fragment.TipsMsgFragment;
import com.proton.carepatchtemp.fragment.dialogfragment.UseNoticeFragment;
import com.proton.carepatchtemp.listener.NoDoubleClickListener;
import com.proton.carepatchtemp.login.activity.LoginAuthActivity;
import com.proton.carepatchtemp.login.activity.LoginFirstActivity;
import com.proton.carepatchtemp.service.BleService;
import com.proton.carepatchtemp.ui.BadgeView;
import com.proton.carepatchtemp.ui.HighLight.HighLight;
import com.proton.carepatchtemp.ui.SegmentView;
import com.proton.carepatchtemp.utils.PermissionUtils;
import com.proton.carepatchtemp.utils.SpUtils;
import com.proton.carepatchtemp.utils.TastyUtils;
import com.proton.carepatchtemp.utils.eventbus.MainEvent;
import com.proton.carepatchtemp.utils.net.DeviceCenter;
import com.proton.carepatchtemp.utils.net.MsgCenter;
import com.proton.carepatchtemp.utils.net.PrfCenter;
import com.proton.carepatchtemp.utils.net.ReportCenter;
import com.proton.carepatchtemp.utils.net.XMPPCenter;
import com.proton.carepatchtemp.utils.ui.StatusBarUtil;
import com.proton.carepatchtemp.utils.ui.ToastUtils;
import com.sdsmdg.tastytoast.TastyToast;

import org.greenrobot.eventbus.EventBus;

import java.lang.ref.WeakReference;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import cn.pedant.SweetAlert.SweetAlertDialog;
import cn.pedant.SweetAlert.Type;

public class MainActivity extends BaseActivity implements ActivityCompat.OnRequestPermissionsResultCallback {

    //ToolBar管理
    public static final int SEARCH_DEVICE = 0;
    public static final int CHOOSE_PROFILE = 1;
    public static final int REAL_TEST = 2;
    public static final int REPORT_LIST = 3;
    public static final int MSG_CENTER = 4;
    public static final int HEALTH_TIPS = 5;
    public static final int SETTINGS = 6;

    //Toolbar 按钮
    protected Intent mServiceIntent;
    List<View> toolbars = new ArrayList<>();
    //  跨进程通信
    private Messenger mMessenger;
    private IncomingHandler mIncomingHandler;
    private ProgressDialog progressDialog;
    private Messenger mService;
    // Content View Elements
    private TextView mTvProfileEdit;
    private RelativeLayout mRtl_ecg_test;
    private ImageView mIv_ecg_menu;
    private RelativeLayout mRtl_test_report;
    private ImageView mIv_test_report_menu;
    private RelativeLayout mRtl_msg_center;
    private ImageView mIv_msg_center_menu;
    private RelativeLayout mRtl_health_tips;
    private ImageView mIv_health_tips_menu;
    private RelativeLayout mRtl_manager_center;
    private ImageView mIv_manager_menu;
    private Toolbar mToolbar;
    private TextView mTv_toolbar_title;
    private TextView mTv_toolbar_new_device;
    private DrawerLayout mDrawer;
    private NavigationView mNavigationView;

    private SearchDevicesFragment mSearchDevicesFragment;
    private ChooseProfileFragment mChooseProfileFragment;
    private SettingFragment mSettingFragment;
    private TipsMsgFragment mTipsMsgFragment;
    private SystemMsgCenterFragment mMsgCenterFragment;
    private ReportListFragment mReportListFragment;
    private RealTimeTestFragment mRealTimeTestFragment;
    private TextView mTv_toolbar_edit;
    private TextView mTv_toolbar_cancel;
    private SegmentView mSg_toolbar_rpt_isCollect;

    private ArrayList<Fragment> mFragments = new ArrayList<>();
    private Fragment mCurrentFrgment;
//    private MenuItem delete_all;
//    private MenuItem consult_box;

    private SimpleDraweeView mSimpleDraweeView;
    private TextView mTv_nav_age;
    private TextView mTv_nav_name;

    private boolean isEditState;

    private BadgeView badge;
    /**
     * 编辑
     */
    private TextView mTvToolbarMsgEdit;
    /**
     * 取消
     */
    private TextView mTvToolbarMsgCancel;
    private PermissionUtils.PermissionGrant mPermissionGrant = requestCode -> {
        switch (requestCode) {
            case PermissionUtils.CODE_RECORD_AUDIO:
                TastyUtils.makeTextShort("Result Permission Grant CODE_RECORD_AUDIO", TastyToast.SUCCESS);
                break;
            case PermissionUtils.CODE_GET_ACCOUNTS:
                TastyUtils.makeTextShort("Result Permission Grant CODE_GET_ACCOUNTS", TastyToast.SUCCESS);
                break;
            case PermissionUtils.CODE_READ_PHONE_STATE:
                TastyUtils.makeTextShort("Result Permission Grant CODE_READ_PHONE_STATE", TastyToast.SUCCESS);
                break;
            case PermissionUtils.CODE_CALL_PHONE:
                TastyUtils.makeTextShort("Result Permission Grant CODE_CALL_PHONE", TastyToast.SUCCESS);
                break;
            case PermissionUtils.CODE_CAMERA:
                TastyUtils.makeTextShort("Result Permission Grant CODE_CAMERA", TastyToast.SUCCESS);
                break;
            case PermissionUtils.CODE_ACCESS_FINE_LOCATION:
                TastyUtils.makeTextShort("Result Permission Grant CODE_ACCESS_FINE_LOCATION", TastyToast.SUCCESS);
                break;
            case PermissionUtils.CODE_ACCESS_COARSE_LOCATION:
                TastyUtils.makeTextShort("Result Permission Grant CODE_ACCESS_COARSE_LOCATION", TastyToast.SUCCESS);
                break;
            case PermissionUtils.CODE_READ_EXTERNAL_STORAGE:
                TastyUtils.makeTextShort("Result Permission Grant CODE_READ_EXTERNAL_STORAGE", TastyToast.SUCCESS);
                break;
            case PermissionUtils.CODE_WRITE_EXTERNAL_STORAGE:
                TastyUtils.makeTextShort("Result Permission Grant CODE_WRITE_EXTERNAL_STORAGE", TastyToast.SUCCESS);
                break;
            case PermissionUtils.CODE_SYSTEM_ALERT_WINDOW:
                TastyUtils.makeTextShort("Result Permission Grant CODE_SYSTEM_ALERT_WINDOW", TastyToast.SUCCESS);
                break;
            case PermissionUtils.CODE_MULTI_PERMISSION:
//                TastyUtils.makeTextShort("Result All Permission Grant", TastyToast.SUCCESS);
                break;
            default:
                break;
        }
    };
    //与服务的连接回调
    private ServiceConnection serviceConnection = new ServiceConnection() {

        // 当与service的连接建立后被调用
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {

            // 客户端(activity) 与 服务 不在同一个进程中的话，是不可以进行显示强制类型转换的
            // 使用从Service返回的IBinder来生成一个Messenger
            mService = new Messenger(service);

            // 生成一个Message
            Message msg = Message.obtain();
            if (msg != null) {
                msg.what = BleService.MSG_REGISTER;
                msg.replyTo = mMessenger;
                // 向Service 发送Message
                sendMessage(msg);
            } else {
                mService = null;
            }
            //activity与service绑定成功
        }

        // 当与service的连接意外断开时被调用
        @Override
        public void onServiceDisconnected(ComponentName name) {
            mService = null;
        }
    };

    @Override
    public void dealEvent(MainEvent event) {
        switch (event.getId()) {
            case Codes.XMPP_SHOW_SERACH:
                showFragment(mSearchDevicesFragment);
                setToolbarState(SEARCH_DEVICE);
                break;
            case Codes.XMPP_SHOW_TEST:
                showFragment(mRealTimeTestFragment);
                initLeftMenu();
                mIv_ecg_menu.setImageResource(R.mipmap.temp_test_on);
                setToolbarState(REAL_TEST);
                break;
            case Codes.NET_PRF_GETLIST:
                if (event.isSuccess()) {
                    showPrfLocal(ProfileManager.getAll().get(0));
                } else {
                    showPrfLocal(null);
                }
                break;
            case Codes.PRF_GO_CHOOSE_PRF:
                if (null == event.getObj()) {
                    TastyUtils.makeTextShort(R.string.get_device_info_failed, TastyToast.ERROR);
                    break;
                }
                if (null != event.getObj()) {
                    mChooseProfileFragment.setTempDevice((Device) event.getObj());
                }
                showFragment(mChooseProfileFragment);
                setToolbarState(CHOOSE_PROFILE);
                break;
            case Codes.PRF_CHOOSE_PRF:
                Profile tempPrf = (Profile) event.getObj();
                if (null == tempPrf) {
//                    TastyUtils.makeTextShort(R.string.get_profile_failed, TastyToast.ERROR);
                    break;
                }
                showFragment(mRealTimeTestFragment);
                setToolbarState(REAL_TEST);
                mRealTimeTestFragment.getTempInfo().setProfile(tempPrf);
                progressDialog.setMessage(getString(R.string.connect_ing));
                progressDialog.show();

                EventBus.getDefault().post(new MainEvent(Codes.BT_CONNECT_DEVICE, mChooseProfileFragment.getTempDevice()));
                break;
            case Codes.BT_CONNECT_FAILED:
                TastyUtils.makeTextShort(R.string.string_connect_fail, TastyToast.ERROR);
                progressDialog.dismiss();
                if (mRealTimeTestFragment.mFragments.size() >= 1) {
                    showFragment(mRealTimeTestFragment);
                    setToolbarState(REAL_TEST);
                } else {
                    showFragment(mSearchDevicesFragment);
                    setToolbarState(SEARCH_DEVICE);
                }
                break;
            case Codes.TEST_SHOW_SEARCH:
                if (mRealTimeTestFragment.mFragments.size() >= 1) {
                    showFragment(mRealTimeTestFragment);
                    setToolbarState(REAL_TEST);
                } else {
                    showFragment(mSearchDevicesFragment);
                    setToolbarState(SEARCH_DEVICE);
                }
                break;
            case Codes.NET_NEED_RELOGIN:
                TastyUtils.makeTextShort(R.string.string_login_agin, TastyToast.DEFAULT);
                break;
            default:
                break;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //锁屏弹窗
        Window win = getWindow();
        WindowManager.LayoutParams winParams = win.getAttributes();
        winParams.flags |= (WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
                | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
                | WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);

        setContentView(R.layout.activity_main);
        initView();
        initToolBar();
        initFragments(mFragments);
        setDrawerLeftEdgeSize(MainActivity.this, mDrawer, 0.5f);
        setListener();
        initMessenger();
        initRequest();
        inityun();
        VCare.get().finishActivity(LoginAuthActivity.class);
        VCare.get().finishActivity(LoginFirstActivity.class);
        bindService(mServiceIntent, serviceConnection, BIND_AUTO_CREATE);

        if (SpUtils.getBoolean(Extras.IS_SHOW_USE_METHOD, true)) {
            UseNoticeFragment useNoticeFragment = UseNoticeFragment.newInstance(null, null);
            useNoticeFragment.show(getSupportFragmentManager(), "shwo_use_course");
        }

        getAliyunToken();
    }

    private void getAliyunToken() {
        ReportCenter.getAliyunToken();
    }

    public void initToolBar() {
        mToolbar.setTitle("");
        setSupportActionBar(mToolbar);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, mDrawer, mToolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        toggle.syncState();
        mToolbar.setNavigationIcon(R.mipmap.icon_toolbar_left);
        mTv_toolbar_new_device.setVisibility(View.GONE);

        toolbars.add(mTvToolbarMsgEdit);
        toolbars.add(mTvToolbarMsgCancel);
        toolbars.add(mSg_toolbar_rpt_isCollect);
        toolbars.add(mTv_toolbar_edit);
        toolbars.add(mTv_toolbar_cancel);
        toolbars.add(mTv_toolbar_title);
        toolbars.add(mTv_toolbar_new_device);
    }

    /**
     * 抽屉滑动范围控制
     */
    private void setDrawerLeftEdgeSize(Activity activity, DrawerLayout drawerLayout, float displayWidthPercentage) {

        if (activity == null || drawerLayout == null)
            return;
        //保持侧滑高亮
        drawerLayout.setScrimColor(0x00ffffff);
        try {
            // 通过反射获取到DrawerLayout的mLeftDragger属性
            Field leftDraggerField = drawerLayout.getClass().getDeclaredField("mLeftDragger");
            leftDraggerField.setAccessible(true);
            ViewDragHelper leftDragger = (ViewDragHelper) leftDraggerField.get(drawerLayout);
            // 找到 edgesize 并设置为 accessible
            Field edgeSizeField = leftDragger.getClass().getDeclaredField("mEdgeSize");
            edgeSizeField.setAccessible(true);
            int edgeSize = edgeSizeField.getInt(leftDragger);
            // 重新设置 edgesize ，以屏幕宽度为比例
            DisplayMetrics dm = new DisplayMetrics();
            activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
            edgeSizeField.setInt(leftDragger, edgeSize);
        } catch (NoSuchFieldException e) {
            Log.e("NoSuchFieldException", e.getMessage());
        } catch (IllegalArgumentException e) {
            Log.e("IllegalArgumentExp", e.getMessage());
        } catch (IllegalAccessException e) {
            Log.e("IllegalAccessException", e.getMessage());
        }
    }

    @Override
    protected void setStatusBar() {
        StatusBarUtil.setColorForDrawerLayout(this, findViewById(R.id.drawer_layout), ContextCompat.getColor(VCare.get(), R.color.colorPrimary), 0);
    }

    public void initFragments(ArrayList<Fragment> mFragments) {
        mChooseProfileFragment = ChooseProfileFragment.newInstance();
        mSearchDevicesFragment = SearchDevicesFragment.getSearchDevicesFragmentInstance();
        mMsgCenterFragment = SystemMsgCenterFragment.newInstance(null, null);
        mTipsMsgFragment = TipsMsgFragment.newInstance();
        mSettingFragment = SettingFragment.getSettingFragment();
        mRealTimeTestFragment = RealTimeTestFragment.newInstance(null, null);

        mFragments.add(mSearchDevicesFragment);
        mFragments.add(mChooseProfileFragment);
        mFragments.add(mMsgCenterFragment);
        mFragments.add(mTipsMsgFragment);
        mFragments.add(mSettingFragment);
        mFragments.add(mRealTimeTestFragment);

        showFragment(mRealTimeTestFragment);
        showFragment(mSearchDevicesFragment);
        mTv_toolbar_edit.setVisibility(View.GONE);
        mTv_toolbar_cancel.setVisibility(View.GONE);
        mTv_toolbar_new_device.setVisibility(View.GONE);
    }

    private void inityun() {
        if (!com.proton.carepatchtemp.constant.Settings.enableShare) {
            return;
        }
        XMPPCenter.loginChat();
    }

    @Override
    public void setListener() {

        mDrawer.addDrawerListener(new DrawerLayout.DrawerListener() {
            @Override
            public void onDrawerSlide(View drawerView, float slideOffset) {
                View mContent = mDrawer.getChildAt(0);
                float Scale = 0.5f * (1.0f + slideOffset);

                if (drawerView.getTag().equals("LEFT")) {
                    drawerView.setAlpha(Scale);
                    ViewHelper.setTranslationX(mContent, drawerView.getMeasuredWidth() * slideOffset);
                    mContent.invalidate();
                } else {
                    drawerView.setAlpha(Scale);
                    ViewHelper.setTranslationX(mContent, -drawerView.getMeasuredWidth() * slideOffset);
                    mContent.invalidate();
                }
            }

            @Override
            public void onDrawerOpened(View drawerView) {
                setBadge();
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                setBadge();
            }

            @Override
            public void onDrawerStateChanged(int newState) {
                setBadge();
            }
        });

        //  档案管理按钮设置监听
        NoDoubleClickListener l3 = new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                isEditState = true;
                Intent goPrfManager = new Intent(MainActivity.this, ProfileManagerActivity.class);
                startActivity(goPrfManager);
                mDrawer.closeDrawers();
            }
        };
        mTvProfileEdit.setOnClickListener(l3);
        //实时测量界面
        NoDoubleClickListener l4 = new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                mTv_toolbar_title.setText(R.string.temp_measure);
//            delete_all.setVisible(false);
//            consult_box.setVisible(false);
                if (!mIncomingHandler.isfirst) {
                    mTv_toolbar_new_device.setVisibility(View.VISIBLE);
                    mTv_toolbar_new_device.setText(R.string.string_new_device);
                }

                initLeftMenu();
                mIv_ecg_menu.setImageResource(R.mipmap.temp_test_on);
                if (mRealTimeTestFragment.mFragments.size() > 0) {
                    showFragment(mRealTimeTestFragment);
                    setToolbarState(REAL_TEST);
                } else {
                    showFragment(mSearchDevicesFragment);
                    setToolbarState(SEARCH_DEVICE);
                }
                mDrawer.closeDrawers();
            }
        };
        mRtl_ecg_test.setOnClickListener(l4);

        //报告列表
        NoDoubleClickListener l5 = new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                mTv_toolbar_title.setText(R.string.report);
                mTv_toolbar_new_device.setVisibility(View.GONE);
                initLeftMenu();
                mIv_test_report_menu.setImageResource(R.mipmap.test_report_on);
                mDrawer.closeDrawers();
                if (null == mReportListFragment) {
                    mReportListFragment = new ReportListFragment();
                    mFragments.add(mReportListFragment);
                }
                showFragment(mReportListFragment);
                setToolbarState(REPORT_LIST);
            }
        };
        mRtl_test_report.setOnClickListener(l5);
        //消息中心
        NoDoubleClickListener l6 = new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                mTv_toolbar_new_device.setVisibility(View.GONE);
                initLeftMenu();
                mIv_msg_center_menu.setImageResource(R.mipmap.msg_center_on);
                mTv_toolbar_title.setText(R.string.info_center);
                mDrawer.closeDrawers();
                showFragment(mMsgCenterFragment);
                setToolbarState(MSG_CENTER);
            }
        };
        mRtl_msg_center.setOnClickListener(l6);
        //反馈信息
        NoDoubleClickListener l7 = new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                mTv_toolbar_new_device.setVisibility(View.GONE);
                mTv_toolbar_title.setText(getString(R.string.string_healthy_tips));
                initLeftMenu();
                mIv_health_tips_menu.setImageResource(R.mipmap.health_tips_on);
                mDrawer.closeDrawers();
                showFragment(mTipsMsgFragment);
                setToolbarState(HEALTH_TIPS);
            }
        };
        mRtl_health_tips.setOnClickListener(l7);
        //管理中心
        NoDoubleClickListener l8 = new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                mTv_toolbar_title.setText(R.string.Settings);
                mTv_toolbar_new_device.setVisibility(View.GONE);
                initLeftMenu();
                mIv_manager_menu.setImageResource(R.mipmap.manager_center_on);
                mDrawer.closeDrawers();
                showFragment(mSettingFragment);
                setToolbarState(SETTINGS);
            }
        };
        mRtl_manager_center.setOnClickListener(l8);
        //新设备
        NoDoubleClickListener l9 = new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                Intent intent = new Intent(MainActivity.this, SearchDevicesActivity.class);
                startActivity(intent);
            }
        };
        mTv_toolbar_new_device.setOnClickListener(l9);
        //取消编辑
        NoDoubleClickListener l10 = new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                mTv_toolbar_new_device.setVisibility(View.GONE);
                mTv_toolbar_cancel.setVisibility(View.GONE);
                mTv_toolbar_edit.setVisibility(View.VISIBLE);
                EventBus.getDefault().post(new MainEvent(Codes.REPORT_CANEL_BULK_DELETION));
            }
        };
        mTv_toolbar_cancel.setOnClickListener(l10);
        //编辑按钮
        NoDoubleClickListener l = new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                mTv_toolbar_new_device.setVisibility(View.GONE);
                mTv_toolbar_edit.setVisibility(View.GONE);
                mTv_toolbar_cancel.setVisibility(View.VISIBLE);
                EventBus.getDefault().post(new MainEvent(Codes.REPORT_BULK_DELETION));
            }
        };
        mTv_toolbar_edit.setOnClickListener(l);

        //报告列表收藏或全部按钮
        SegmentView.onSegmentViewClickListener onSegmentViewClickListener = (v, position) -> {
            switch (position) {
                case 0:
                    EventBus.getDefault().post(new MainEvent(Codes.REPORT_GET_ALL));
                    break;
                case 1:
                    EventBus.getDefault().post(new MainEvent(Codes.REPORT_GET_COLLECT));
                    break;
                default:
                    break;
            }
        };
        mSg_toolbar_rpt_isCollect.setOnSegmentViewClickListener(onSegmentViewClickListener);

        NoDoubleClickListener l1 = new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                mTvToolbarMsgEdit.setVisibility(View.GONE);
                mTvToolbarMsgCancel.setVisibility(View.VISIBLE);
                EventBus.getDefault().post(new MainEvent(Codes.MSG_BULK_DELETION));
            }
        };
        mTvToolbarMsgEdit.setOnClickListener(l1);

        NoDoubleClickListener l2 = new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                mTvToolbarMsgCancel.setVisibility(View.GONE);
                mTvToolbarMsgEdit.setVisibility(View.VISIBLE);
                EventBus.getDefault().post(new MainEvent(Codes.MSG_CANCEL_BULK_DELETION));
            }
        };
        mTvToolbarMsgCancel.setOnClickListener(l2);
    }

    public void initRequest() {
        DeviceCenter.getList();
        DeviceCenter.getUpdateFirmWare("V1.0.0");
        PrfCenter.getlist();
        MsgCenter.msggetlist(1, Extras.DVC_TYPE_TMP);
        mIncomingHandler.postDelayed(() -> checkUpdate(), 3000);
    }

    private void checkUpdate() {
        if (VCare.get().needUpdate > 0) {
            SweetAlertDialog dialog = new SweetAlertDialog(this, Type.NORMAL_TYPE);
            dialog.setCancelable(false);
            dialog.setTitleText(getString(R.string.string_find_new_hardware));
            dialog.setContentText(getString(R.string.string_upgrade_in_time));
            dialog.showCancelButton(true);
            dialog.setConfirmText(getString(R.string.string_upgrade));
            dialog.setCancelText(getString(R.string.string_cancel));
            dialog.setCancelClickListener(Dialog::dismiss);
            dialog.setConfirmClickListener(sweetAlertDialog -> {
                Intent intent = new Intent(this, DeviceManagerActivity.class);
                startActivity(intent);
            });
            dialog.show();
        }
    }

    private void initMessenger() {
        mIncomingHandler = new IncomingHandler(this);
        mMessenger = new Messenger(mIncomingHandler);

        progressDialog = new ProgressDialog(this);
        progressDialog.setCancelable(false);
        mServiceIntent = new Intent(this, BleService.class);
    }

    @Override
    protected void onStart() {
        super.onStart();
        // TODO: 2016/12/29 弹窗权限需要完善
        PermissionUtils.requestMultiPermissions(this, mPermissionGrant);
    }

    @Override
    protected void onResume() {
        super.onResume();
        checkFloatPermission();
        showGuide();
    }

    private void showGuide() {
        //观看过视频后才会显示引导
        if (com.proton.carepatchtemp.constant.Settings.isPlayerTv && SpUtils.getBoolean(Extras.FIRST_WATCH_TV, true)) {
            addHightView();
        }

    }

    private void checkFloatPermission() {
        try {
            if (VCare.hasCheckFloatPermission) {
                return;
            }
            VCare.hasCheckFloatPermission = true;
            if (Build.VERSION.SDK_INT >= 23) {
                if (!Settings.canDrawOverlays(this)) {
                    AlertDialog.Builder normalDialog =
                            new AlertDialog.Builder(this);
                    normalDialog.setIcon(R.mipmap.ic_launcher);
                    normalDialog.setTitle(R.string.string_tips);
                    normalDialog.setMessage(R.string.string_warm);
                    normalDialog.setPositiveButton(getText(R.string.string_confirm),
                            (dialog, which) -> {
                                Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                                        Uri.parse("package:" + getPackageName()));
                                startActivity(intent);
                                TastyUtils.makeText(R.string.string_warm2, TastyToast.LENGTH_LONG, TastyToast.DEFAULT);
                                dialog.dismiss();
                            });
                    normalDialog.setNegativeButton(getString(R.string.string_cancel),
                            (dialog, which) -> {
                            });
                    // 显示
                    normalDialog.show();

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void addHightView() {
        SpUtils.saveBoolean(Extras.FIRST_WATCH_TV, false);
        HighLight highLight = new HighLight(this)
                .anchor(findViewById(R.id.drawer_layout)) //绑定根布局，在Activity中可不写
                .setIntercept(true) // 查看注释和代码，可设置其他属性
                .setIsNeedBorder(false)
                .setShadow(true)
                .addHighLight(android.R.id.home, R.layout.left_top_drawer, new HighLight.OnPosCallback() {
                    @Override
                    public void getPos(float rightMargin, float bottomMargin, RectF rectF, HighLight.MarginInfo marginInfo) {

                        marginInfo.leftMargin = rectF.right - rectF.width() / 2;
                        marginInfo.topMargin = rectF.bottom;

                    }
                });
        highLight.show();

        highLight.setChildOnClickListener(R.id.iv_next_step, v -> {
            highLight.remove();
            mDrawer.openDrawer(Gravity.START);
            showSecondHightView();
        });

        highLight.setChildOnClickListener(R.id.tv_skip, v -> highLight.remove());
    }

    private void showSecondHightView() {
        mRtl_manager_center.postDelayed(() -> {
            HighLight highLight = new HighLight(this)
                    .anchor(findViewById(R.id.drawer_layout)) //绑定根布局，在Activity中可不写
                    .setIntercept(false) // 查看注释和代码，可设置其他属性
                    .setIsNeedBorder(false)
                    .setIntercept(true)
                    .setShadow(true)
                    .addHighLight(R.id.rtl_manager_center, R.layout.left_bottom_drawer, new HighLight.OnPosCallback() {
                        @Override
                        public void getPos(float rightMargin, float bottomMargin, RectF rectF, HighLight.MarginInfo marginInfo) {
                            marginInfo.leftMargin = rectF.width() / 2;
                            marginInfo.bottomMargin = bottomMargin + rectF.height();

                        }
                    });
            highLight.show();

            highLight.setChildOnClickListener(R.id.iv_next_step, v -> {
                highLight.remove();
                mRtl_manager_center.performClick();
                mRtl_manager_center.postDelayed(() -> mSettingFragment.showHighLight(), 300);
            });
        }, 300);

    }

    @Override
    protected void onDestroy() {
        progressDialog.dismiss();
        progressDialog = null;
        mIncomingHandler.removeCallbacksAndMessages(null);
        unbindService(serviceConnection);
        super.onDestroy();
    }

    // End Of Content View Elements
    private void initView() {
        mToolbar = findViewById(R.id.toolbar);
        mTv_toolbar_title = findViewById(R.id.tv_toolbar_title);
        mTv_toolbar_new_device = findViewById(R.id.tv_toolbar_new_device);
        mTv_toolbar_edit = findViewById(R.id.tv_toolbar_edit);
        mTv_toolbar_cancel = findViewById(R.id.tv_toolbar_cancel);
        mDrawer = findViewById(R.id.drawer_layout);
        mNavigationView = findViewById(R.id.nav_view);
        mSimpleDraweeView = mNavigationView.getHeaderView(0).findViewById(R.id.sdv_profile_avatar);  //NavigationView得到对象
        mTv_nav_name = mNavigationView.getHeaderView(0).findViewById(R.id.tv_nav_name);
        mTv_nav_age = mNavigationView.getHeaderView(0).findViewById(R.id.tv_nav_age);
        mTvProfileEdit = mNavigationView.getHeaderView(0).findViewById(R.id.tv_profile_manager);
        mSg_toolbar_rpt_isCollect = findViewById(R.id.sv_is_collect);
        mSg_toolbar_rpt_isCollect.setSegmentText("   " + getString(R.string.string_all) + "   ", 0);
        mSg_toolbar_rpt_isCollect.setSegmentText(getString(R.string.string_marked), 1);
        mTvToolbarMsgEdit = findViewById(R.id.tv_toolbar_msg_edit);
        mTvToolbarMsgCancel = findViewById(R.id.tv_toolbar_msg_cancel);

        mRtl_ecg_test = findViewById(R.id.rtl_ecg_test);
        mIv_ecg_menu = findViewById(R.id.iv_ecg_menu);
        mRtl_test_report = findViewById(R.id.rtl_test_report);
        mIv_test_report_menu = findViewById(R.id.iv_test_report_menu);
        mRtl_msg_center = findViewById(R.id.rtl_msg_center);
        mIv_msg_center_menu = findViewById(R.id.iv_msg_center_menu);
        mRtl_health_tips = findViewById(R.id.rtl_health_tips);
        mIv_health_tips_menu = findViewById(R.id.iv_health_tips_menu);
        mRtl_manager_center = findViewById(R.id.rtl_manager_center);
        mIv_manager_menu = findViewById(R.id.iv_manager_menu);

        if (VCare.isInternal) {
            mRtl_health_tips.setVisibility(View.GONE);
        }
    }

    private void setBadge() {
        if (badge == null) {
            badge = new BadgeView(new WeakReference<Activity>(this).get());
            badge.setScaleX(0.5F);
            badge.setScaleY(0.5f);
            badge.setTargetView(mIv_manager_menu);
            badge.setTextColor(Color.RED);
            badge.setBadgeCount(1);
        }

        if (VCare.get().needUpdate <= 0) {
            badge.setVisibility(View.GONE);
        } else {
            badge.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 初始化侧拉菜单图标
     */
    private void initLeftMenu() {
        mIv_ecg_menu.setImageResource(R.mipmap.temp_test_off);
        mIv_test_report_menu.setImageResource(R.mipmap.test_report_off);
        mIv_msg_center_menu.setImageResource(R.mipmap.msg_center_off);
        mIv_health_tips_menu.setImageResource(R.mipmap.health_tips_off);
        mIv_manager_menu.setImageResource(R.mipmap.manager_center_off);
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else if (mRealTimeTestFragment.isHidden() && mRealTimeTestFragment.mFragments.size() > 0) {
            initLeftMenu();
            mIv_ecg_menu.setImageResource(R.mipmap.temp_test_on);
            showFragment(mRealTimeTestFragment);
            setToolbarState(REAL_TEST);
        } else if (mRealTimeTestFragment.mFragments.size() > 0) {
            moveTaskToBack(true);
        } else {
            moveTaskToBack(true);
        }
    }

//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        if (Codes.BT_START_SEARCH_DEVICE == requestCode && RESULT_OK == resultCode){
//
//            showFragment(mChooseProfileFragment);
//        }
//    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
//        getMenuInflater().inflate(R.menu.main, menu);
//        delete_all=menu.findItem(R.deviceId.action_delete);
//        consult_box=menu.findItem(R.deviceId.action_consult_box);
//        delete_all.setVisible(false);
//        consult_box.setVisible(false);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {  //toolbar上对象的点击事件
        int id = item.getItemId();
        switch (id) {
//            case R.deviceId.action_delete:
//                new MainEvent(Codes.REPORT_BULK_DELETION).post();
//                break;
//            case R.deviceId.action_consult_box:
//                Intent intent = new Intent(MainActivity.this,ConsultBoxActivity.class);
//                startActivity(intent);
//                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onEventMainThread(MainEvent event) {
        dealOnEvent(event);
    }

    private void showFragment(Fragment frag) {
        try {

            if (MainActivity.this.isDestroyed()) {
                LogUtils.e("MainActivity is Destroyed");
                return;
            }

            //先根据Tag从FragmentTransaction事物获取之前添加的Fragment
            LogUtils.d(frag.getClass().getSimpleName());
            Fragment fragment = getSupportFragmentManager().findFragmentByTag(frag.getClass().getSimpleName());

            if (null == fragment) {
                LogUtils.e(frag.getClass().getSimpleName() + " is null");
                //如fragment为空，则之前未添加此Fragment。便从集合中取出
                fragment = frag;
            }
            mCurrentFrgment = fragment;

            //判断当前的Fragment是否为空，不为空则隐藏
            //  隐藏其他不需要显示的fragment
            for (Fragment temp : mFragments) {
                if (!temp.isHidden() && !temp.getClass().getSimpleName().equalsIgnoreCase(mCurrentFrgment.getClass().getSimpleName())) {
                    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
                    //ft.setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_left, R.anim.slide_in_right, R.anim.slide_out_left);
                    ft.hide(temp).commit();
                }
            }
            //判断此Fragment是否已经添加到FragmentTransaction事物中
            if (!fragment.isAdded()) {
                FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
                //ft.setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_left, R.anim.slide_in_right, R.anim.slide_out_left);
                ft.add(R.id.content_main, fragment, fragment.getClass().getSimpleName()).show(fragment).commit();
            } else {
                FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
                //ft.setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_left, R.anim.slide_in_right, R.anim.slide_out_left);
                ft.show(fragment).commit();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void setToolbarState(int which) {
        for (View v :
                toolbars) {
            if (v.getVisibility() == View.VISIBLE)
                v.setVisibility(View.GONE);
        }

        switch (which) {
            //搜索界面
            case SEARCH_DEVICE:
                mTv_toolbar_title.setVisibility(View.VISIBLE);
                break;
            //档案选择界面
            case CHOOSE_PROFILE:
                mTv_toolbar_title.setVisibility(View.VISIBLE);
                mTv_toolbar_new_device.setVisibility(View.VISIBLE);
                mTv_toolbar_new_device.setText(R.string.string_research);
                break;
            //实时测量
            case REAL_TEST:
                mTv_toolbar_title.setVisibility(View.VISIBLE);
                mTv_toolbar_new_device.setVisibility(View.VISIBLE);
                mTv_toolbar_new_device.setText(R.string.string_new_device);
                break;
            //测量报告
            case REPORT_LIST:
                mSg_toolbar_rpt_isCollect.setVisibility(View.VISIBLE);
                mTv_toolbar_edit.setVisibility(View.VISIBLE);
                break;
            //消息中心
            case MSG_CENTER:
                mTv_toolbar_title.setVisibility(View.VISIBLE);
                mTvToolbarMsgEdit.setVisibility(View.VISIBLE);
                break;
            //健康贴士
            case HEALTH_TIPS:
                mTv_toolbar_title.setVisibility(View.VISIBLE);
                break;
            //管理中心
            case SETTINGS:
                mTv_toolbar_title.setVisibility(View.VISIBLE);
                break;
            default:
                break;
        }
    }

    public boolean showPrfLocal(Profile showPrf) {
        if (null == showPrf) {
            mSimpleDraweeView.setController(null);
            mTv_nav_name.setText("---");
            mTv_nav_age.setText("--" + getString(R.string.sui));
            return false;
        }
        //LogUtils.e(prf);
        mSimpleDraweeView.setImageURI(showPrf.getAvatar());
        mTv_nav_name.setText(showPrf.getRealname());
        mTv_nav_age.setText(showPrf.getAge() + getString(R.string.sui));

        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        PermissionUtils.requestPermissionsResult(this, requestCode, permissions, grantResults, mPermissionGrant);
    }

    protected synchronized void sendMessage(Message msg) {
        if (msg != null && mService != null) {
            try {
                mService.send(msg);
            } catch (RemoteException e) {
                unbindService(serviceConnection);
            }
        }
    }

    private class IncomingHandler extends Handler {

        private final WeakReference<MainActivity> mActivity;
        private boolean isfirst = true;

        public IncomingHandler(MainActivity activity) {
            mActivity = new WeakReference<>(activity);
        }

        /*
         * 处理从Service发送至该Activity的消息
         */
        @Override
        public void handleMessage(Message msg) {
            MainActivity activity = mActivity.get();

            if (activity != null) {
                switch (msg.what) {
                    case BleService.MSG_NOT_FOUND_DEVICE_SERVICE:
                        activity.progressDialog.dismiss();
                        showFragment(mSearchDevicesFragment);
                        setToolbarState(SEARCH_DEVICE);
                        ToastUtils.i("");
                        TastyUtils.makeTextShort(R.string.search_no_service, TastyToast.DEFAULT);
                        break;
                    case BleService.MSG_SEND_DATA:
                        progressDialog.dismiss();
                        LogUtils.d(msg.obj);
                        EventBus.getDefault().post(new MainEvent(Codes.BT_SEND_TEMP_DATA, msg));
                        break;
                    case 1:
                        LogUtils.d(msg.obj);
                        break;
                    case BleService.MSG_DEVICE_CONNECT_STATE:
//                        if (!(boolean) msg.obj) {
//                            progressDialog.dismiss();
                        TastyUtils.makeTextShort(R.string.device_disconnect, TastyToast.DEFAULT);
//                            // TODO: 2016/11/22 fragment切换问题，待解决
//                            showFragment(mSearchDevicesFragment);
//                            getSupportFragmentManager().beginTransaction().remove(getSupportFragmentManager().findFragmentByTag("rt")).show(mSearchDevicesFragment).commit();
//                        }
                        break;
                    case BleService.MSG_ADD_DEVICE_CONNECT:
                        progressDialog.dismiss();
                        if (null != msg.obj) {
                            Device tempDevice = (Device) msg.obj;
                            if (mRealTimeTestFragment.mList.containsKey(tempDevice.getBtaddress())) {
                                EventBus.getDefault().post(new MainEvent(tempDevice.getBtaddress(), Codes.BT_ADD_DEVICE_CONNECT, msg.obj));
                            } else {
                                if (isfirst) {
                                    showFragment(mRealTimeTestFragment);
                                    isfirst = false;
                                }
                                setToolbarState(REAL_TEST);
                                EventBus.getDefault().post(new MainEvent(tempDevice.getBtaddress(), Codes.BT_ADD_DEVICE_CONNECT, msg.obj));
                            }
                        }
                        break;

                    //连接失败
                    case BleService.MSG_DEVICE_CONNECT_FAILED:
                        progressDialog.dismiss();
                        if (mRealTimeTestFragment.mFragments.size() >= 1) {
                            showFragment(mRealTimeTestFragment);
                            setToolbarState(REAL_TEST);
                        } else {
                            showFragment(mSearchDevicesFragment);
                            setToolbarState(SEARCH_DEVICE);
                        }
                        TastyUtils.makeTextShort(R.string.string_connect_fail, TastyToast.ERROR);
                        break;
                    default:
//                        TastyUtils.makeTextShort(msg.what + "   default" + (String)msg.obj, TastyToast.INFO);
                        break;
                }
            }

        }
    }

}
